package org.example.contract.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.example.contract.domain.ContractFile;
import org.example.contract.domain.ContractPartner;
import org.example.contract.domain.ContractProduct;
import org.example.contract.mapper.ContractFileMapper;
import org.example.contract.mapper.ContractPartnerMapper;
import org.example.contract.mapper.ContractProductMapper;
import org.example.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.contract.mapper.ContractMapper;
import org.example.contract.domain.Contract;
import org.example.contract.service.IContractService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 合同管理Service业务层处理
 *
 * @author 小孟微信：xiaomengcode
 * @date 2024-04-11
 */
@Service
public class ContractServiceImpl implements IContractService
{
    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private ContractProductMapper contractProductMapper;

    @Autowired
    private ContractFileMapper contractFileMapper;


    @Autowired
    private ContractPartnerMapper contractPartnerMapper;



    /**
     * 查询合同管理
     *
     * @param contractId 合同管理主键
     * @return 合同管理
     */
    @Override
    public Contract selectContractByContractId(Long contractId)
    {
        return contractMapper.selectContractByContractId(contractId);
    }

    /**
     * 查询合同管理列表
     *
     * @param contract 合同管理
     * @return 合同管理
     */
    @Override
    @DataScope(userAlias = "u",deptAlias = "d")
    public List<Contract> selectContractList(Contract contract)
    {
        if("0".equals(contract.getRoleFlag())){//租户
            Util.setQuerySelfData((BaseEntity) contract);
            return contractMapper.selectContractList(contract);
        }else{//合作伙伴
            contract.setBuyDeptId(ShiroUtils.getSysUser().getDeptId());
            contract.setOwnerDeptId(ShiroUtils.getSysUser().getDeptId());
            return contractMapper.selectContractList(contract);
        }
    }

    /**
     * 新增合同管理
     *
     * @param contract 合同管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertContract(Contract contract)
    {
        contract.setContractCode(getContractCode(contract.getContractType()));
        contract.setCreateBy(ShiroUtils.getUserId()+"");
        contract.setCreateTime(DateUtils.getNowDate());
        List<ContractProduct> list =getList(contract);
        contract.setTotalNum(getTotalNum(list));
        contract.setTotalMoney(getTotalMoney(list));
        int i= contractMapper.insertContract(contract);
        insertQingDanAndContractFile(contract,list);



        //合作伙伴
        if(Util.CONTRACT_TYPE_BUY.equals(contract.getContractType())){
            //采购合同
            ContractPartner ownerPartner =
                    new ContractPartner(contract.getContractId(),contract.getOwnerDeptId(),Util.CONTRACT_TYPE_BUY,contract.getCreateBy());
            contractPartnerMapper.insertContractPartner(ownerPartner);

            ContractPartner buyPartner =
                    new ContractPartner(contract.getContractId(),contract.getBuyDeptId(),Util.CONTRACT_TYPE_SELL,contract.getCreateBy());
            contractPartnerMapper.insertContractPartner(buyPartner);
        }else{
            //销售合同
            ContractPartner ownerPartner =
                    new ContractPartner(contract.getContractId(),contract.getOwnerDeptId(),Util.CONTRACT_TYPE_SELL,contract.getCreateBy());
            contractPartnerMapper.insertContractPartner(ownerPartner);

            ContractPartner buyPartner =
                    new ContractPartner(contract.getContractId(),contract.getBuyDeptId(),Util.CONTRACT_TYPE_BUY,contract.getCreateBy());
            contractPartnerMapper.insertContractPartner(buyPartner);
        }

        return i;
    }
    private String getContractCode(String contractType) {
        Long deptId=ShiroUtils.getSysUser().getDeptId();
//        String ancestors= ShiroUtils.getSysUser().getDept().getAncestors();
//        String[] strArray = Convert.toStrArray(ancestors);
//        if(strArray.length==3){
//            deptId=Long.parseLong(strArray[strArray.length-1]);
//        }

        Contract contract=new Contract();
        contract.getParams().put("deptId",deptId);
        contract.setCreateTime(DateUtils.getNowDate());
        contract.setContractType(contractType);
        List<Contract> list =contractMapper.selectDeptContractList(contract);
        int total=0;
        if(list !=null && list.size()>0){
            total=list.size();
        }
        String s2 = String.format("%04d", total+1);

        String contractCode = null;
        if(Util.CONTRACT_TYPE_SELL.equals(contractType)){
            //销售
            contractCode =  "SO"+DateUtils.dateTimeNow("yyMMdd")+s2;
        }else{
            //采购
            contractCode =  "PO"+DateUtils.dateTimeNow("yyMMdd")+s2;
        }
        return contractCode;
    }

    //总数量
    private Integer getTotalNum(List<ContractProduct> list){
        int total=0;
        for(ContractProduct cart:list){
            if(cart.getNum()!=null){
                total +=cart.getNum();
            }
        }
        return total;
    }

    //合同总价
    private BigDecimal getTotalMoney(List<ContractProduct> list){
        BigDecimal totalMoney= BigDecimal.valueOf(0);
        for(ContractProduct cart:list){
            totalMoney=cart.getPrice().multiply(BigDecimal.valueOf(cart.getNum())).add(totalMoney);
        }
        return totalMoney;
    }


    //采购列表
    private List<ContractProduct> getList(Contract contract){
        List<ContractProduct> list =new ArrayList<>();
        if(contract.getParams().containsKey("qingdan")) {
            String qingdan = contract.getParams().get("qingdan").toString();
            list = JSONUtil.parseArray(qingdan).toList(ContractProduct.class);
        }
        return list;
    }

    /**
     * 新增合同清单和合同附件
     */
    private void insertQingDanAndContractFile(Contract contract,List<ContractProduct> list) {
        //合同清单
        if(contract.getParams().containsKey("qingdan")){
            for(ContractProduct cart:list){
                cart.setRemainNum(cart.getNum());
                cart.setCreateBy(contract.getCreateBy());
                cart.setCreateTime(contract.getCreateTime());
                cart.setContractId(contract.getContractId()+"");
                contractProductMapper.insertContractProduct(cart);
            }
        }
        //合同附件
        if(contract.getParams().containsKey("contractFile")){
            String contractFile= contract.getParams().get("contractFile").toString();
            List<ContractFile> listFile = JSONUtil.parseArray(contractFile).toList(ContractFile.class);
            for(ContractFile file:listFile){
                file.setCreateBy(contract.getCreateBy());
                file.setCreateTime(contract.getCreateTime());
                file.setContractId(contract.getContractId()+"");
                contractFileMapper.insertContractFile(file);
            }
        }
    }


    /**
     * 修改合同管理
     *
     * @param contract 合同管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateContract(Contract contract)
    {
        contractProductMapper.deleteContractProductByContractId(contract.getContractId());
        contractFileMapper.deleteContractFileByContractId(contract.getContractId());
        contract.setCreateBy(ShiroUtils.getUserId()+"");
        List<ContractProduct> list =getList(contract);
        contract.setTotalNum(getTotalNum(list));
        contract.setTotalMoney(getTotalMoney(list));
        insertQingDanAndContractFile(contract,list);


        //合作伙伴
        if(Util.CONTRACT_TYPE_BUY.equals(contract.getContractType())){
            //采购合同
            ContractPartner ownerPartner =
                    new ContractPartner(contract.getContractId(),contract.getOwnerDeptId(),Util.CONTRACT_TYPE_BUY,contract.getCreateBy());
            contractPartnerMapper.updateContractPartnerByContractId(ownerPartner);

            ContractPartner buyPartner =
                    new ContractPartner(contract.getContractId(),contract.getBuyDeptId(),Util.CONTRACT_TYPE_SELL,contract.getCreateBy());
            contractPartnerMapper.updateContractPartnerByContractId(buyPartner);
        }else{
            //销售合同
            ContractPartner ownerPartner =
                    new ContractPartner(contract.getContractId(),contract.getOwnerDeptId(),Util.CONTRACT_TYPE_SELL,contract.getCreateBy());
            contractPartnerMapper.updateContractPartnerByContractId(ownerPartner);

            ContractPartner buyPartner =
                    new ContractPartner(contract.getContractId(),contract.getBuyDeptId(),Util.CONTRACT_TYPE_BUY,contract.getCreateBy());
            contractPartnerMapper.updateContractPartnerByContractId(buyPartner);
        }


        return contractMapper.updateContract(contract);
    }

    /**
     * 批量删除合同管理
     *
     * @param contractIds 需要删除的合同管理主键
     * @return 结果
     */
    @Override
    public int deleteContractByContractIds(String contractIds)
    {
        return contractMapper.deleteContractByContractIds(Convert.toStrArray(contractIds));
    }

    /**
     * 删除合同管理信息
     *
     * @param contractId 合同管理主键
     * @return 结果
     */
    @Override
    public int deleteContractByContractId(Long contractId)
    {
        contractPartnerMapper.deleteContractPartnerByContractId(contractId);
        return contractMapper.deleteContractByContractId(contractId);
    }
}
